package com.leyou.auth.service.impl;

import com.leyou.auth.dto.UserDetail;
import com.leyou.auth.service.UserAuthService;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.dto.UserDTO;
import com.leyou.exception.LyException;
import com.leyou.user.client.UserClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

@Service
public class UserAuthServiceImpl implements UserAuthService {

    @Autowired
    private UserClient userClient;

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public void login(String username, String password, HttpServletResponse response) {

        /**
         * 根据前端用户名和密码去数据库中查找是否有
         */
        UserDTO userDTO = userClient.queryUserByUsernameAndPassword(username, password);
        if (userDTO == null) {
            throw new LyException(400,"用户名或者密码错误");
        }

        UserDetail userDetail = UserDetail.of(userDTO.getId(), userDTO.getUsername());

        String jwt = jwtUtils.createJwt(userDetail);

        writeCookie(response,jwt);


    }

    private void writeCookie(HttpServletResponse response, String token) {

        Cookie ly_cookie = new Cookie("LY_COOKIE", token);
        //是否禁止JS操作cookie
        ly_cookie.setHttpOnly(true);
        //cookie的有效期，-1代表当前会话，浏览器关闭后消失
        ly_cookie.setMaxAge(-1);
        //cookie的作用路径
        ly_cookie.setPath("/");

        response.addCookie(ly_cookie);



    }
}
